//
//  GZchuLiQRVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/12.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "GZchuLiQRVC.h"

@interface GZchuLiQRVC ()
{
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property(strong,nonatomic) UITableView *listTableview;
@property(strong,nonatomic) NSMutableArray *dataList;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(nonatomic,strong) NSMutableArray *GZid;
@property (nonatomic,strong)NSMutableArray *allData;
@property(strong,nonatomic) AFHTTPSessionManager *manager;
@end

@implementation GZchuLiQRVC
- (AFHTTPSessionManager *)manager{

    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.listTableview.mj_header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"故障处理确认";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    //读取保存在中间对象中的数据
    UIApplication *app = [UIApplication sharedApplication];
    
    AppDelegate *delegate = app.delegate;
    self.userId = delegate.userId;
    _allData = [[NSMutableArray alloc]init];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
        [self setData];
    });



}
//设置UI视图
-(void)initView
{
    self.listTableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH,kSCREEN_HEIGHT) style:UITableViewStylePlain];
    self.listTableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.listTableview.delegate=self;
    self.listTableview.dataSource=self;
    self.listTableview.rowHeight = 62.0;
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.listTableview setTableFooterView:v];
    [self.view addSubview:self.listTableview];
    self.listTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self setData];
    }];
}
/**
 *  停止刷新
 */
-(void)endRefresh{
    
    [self.listTableview.mj_header endRefreshing];
    
}
//数据
-(void)setData
{
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";

    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_chuliQR parameters:@{userid:[NSString stringWithFormat:@"%ld",self.userId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dicdate = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        NSDictionary *data = dicdate[@"data"];
        NSArray *arr = data[@"ohrstlist"];
        GZdataModel *model = [[GZdataModel alloc]initWithDictionary:dicdate[@"data"] error:nil];
        for (OhlistModel *listModel in model.ohrstlist) {
            
            [_allData addObject:listModel];
            
        }
        
        self.dataList=[NSMutableArray arrayWithCapacity:0];
        self.dataSource = [[NSMutableArray alloc]init];
        _GZid = [[NSMutableArray alloc]init];
        for (NSInteger i = 0; i<arr.count; ++i) {
            
            NSString *strTime = [NSString stringWithFormat:@"%@",arr[i][@"time"]];
            
            NSString *Month_str = [strTime substringWithRange:NSMakeRange(5, 2)];
            NSString *Day_str = [strTime substringWithRange:NSMakeRange(8, 2)];
            NSString *Time = [NSString stringWithFormat:@"%@/%@",Month_str,Day_str];
            
            NSDictionary *dic=@{@"timeStr":Time,@"titleStr":arr[i][@"title"],@"averageScoreStr":arr[i][@"fixResult"],@"state":arr[i][@"state"]};
            TimeModel *model=[[TimeModel alloc]initData:dic];
            [self.dataList addObject:model];
            canshuModel *model1 = [[canshuModel alloc]init];
            model1.Parid = [arr[i][@"id"]integerValue];
            [self.dataSource addObject:model1];
            
        }

        if (self.dataList.count == 0) {
            
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"没有要确认事件"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }else{
            
            [self initView];
            [self.listTableview reloadData];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0,64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }


    }];
    
}
- (void)NothingRefresh:(UIButton *)sender{
    [_nothing removeFromSuperview];
    [self setData];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self setData];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self setData];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self setData];
}

#pragma mark-----------------------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId=@"testTime";
    RightSlidetableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell=[[RightSlidetableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    TimeModel *model=self.dataList[indexPath.row];
    [cell setData:model];
    //self.listTableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OhlistModel *model = _allData[indexPath.row];
    canshuModel *model1 = _dataSource[indexPath.row];
    
    GZchuliQRmassagerVC *vc = [[GZchuliQRmassagerVC alloc]init];
    vc.orID = model1.Parid;
    vc.section1 = @[model.station,model.equip,model.equipBrand,model.equipModel,model.faultTime];
    vc.section2 = @[model.fixName,model.faultLevel,model.fixType,[NSString stringWithFormat:@"%ld小时",model.fixTime],model.fixMtPcs,model.fixResult];
    vc.imageArr = [model.images componentsSeparatedByString:@","];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
